// pages/energy/energy.js
const recorderManager = wx.getRecorderManager();
// 播放器
const innerAudioContext = wx.createInnerAudioContext();
const app = getApp()
var router = require("../../router.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sxyy: '',
    chose_music: false,
    start: '开始',
    yinpin: '',
    pictrueTempPath: "", // 临时途径
    soundRecording: {
      tempPath: "",
      duration: "",
      isPlay: false,// 临时录音
      play: true,
    },
    allmusic: [
    ],
    xphoto: '/images/upload.png',
    isnum: 3,
  },
  start_music: function () {
    this.setData({
      chose_music: true
    })
  },
  start_sure: function () {
    this.setData({
      chose_music: false
    })
  },
  start_chosedeil: function (e) {
    var _index = e.currentTarget.dataset.index;  //获取自定义的ID值 
    var xianshiyy = this.data.sxyy; //显示音乐
    var music = this.data.allmusic;
    var kss = music[_index].name;
    xianshiyy = kss;
    let currentMusic = this.data.allmusic[_index];
    let result = this.playMusic({
      url: currentMusic.music,
      title: currentMusic.name,
      img: currentMusic.img
    });
    this.setData({
      chose_music: false,
      sxyy: xianshiyy,
    });
  },
  /**
   * 音乐播放
   */
  playMusic: function ({ url: url, title: title, img: img }) {
    wx.playBackgroundAudio({
      dataUrl: url,
      title: title,
      //图片地址地址
      coverImgUrl: img
    })
  },
  //上传图片  
  xphotos: function () {
    var that = this;
    var xphoto = that.data.xphoto;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片      
        wx.uploadFile({
          url: router.msg.upload,
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            uploadType: 'img'
          },
          success: function (res) {            
            var result = JSON.parse(res.data);
            if (result.status) {
              that.setData({
                xphoto: result.path
              });
            }
            else {
              wx.showToast({
                title: '图片上传失败请重试',
                content: '图片上传失败请重试',
                icon: 'none'
              })
            }
          }
        })
      },
    })
  },
  release: function () {
    var that = this;
    var title = that.data.title;
    var xphoto = that.data.xphoto;
    var yinpin = that.data.yinpin;
    var duration = that.data.soundRecording.duration;
    if (title && xphoto != '/images/upload.png' && yinpin && duration) {
      app.request({
        url: router.msg.add,
        method: "POST",
        data: {
          uid: wx.getStorageSync('uid'),
          title: title,
          xphoto: xphoto,
          yinpin: yinpin,
          duration: duration
        },
        success: function (data) {        
          if (data) {           
            wx.showToast({
              title: '发布成功',
              icon: 'none'
            });
            setTimeout(function () {
              app.navTo('../speaklist/speaklist')               
            }, 1500);
          } else {
            wx.showToast({
              title: '发布失败,请重试',
              icon: 'none'
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '请确保标题图片录音完成再进行此操作',
        duration: 2000,
        icon: 'none'
      })
    }
  },
  onLoad: function (options) {
    var that = this;
    app.request({
      url: router.msg.getMusic,    
      success: function (data) {        
        if (data) {         
          for (var i = 0; i < data.length; i++) {
            that.data.allmusic.push(data[i]);
          }
          that.setData({           
            allmusic: that.data.allmusic
          });
        }
      }
    })   
  },
  changeInputData: function (e) {
    var inputVlaue = e.detail.value;   
    this.setData({
      title: inputVlaue
    });    
  },
  /**
   * 录音开始
   */
  soundRecordingStart: function () {
    this.setData({
      start: '正在录音'
    })
    const options = {
      duration: 600000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }
    recorderManager.start(options);
  },
  /**
   * 录音完成
   */
  soundRecordingEnd: function () {
    var i = this.data.start;
    var st;
    if (i == '正在录音') {
      st = "录音结束"
    } else {
      st = "正在录音"
    }
    this.setData({
      start: st
    })
    let _this = this;
    recorderManager.stop();
    recorderManager.onStop(function (res) {
      let _tempPath = res.tempFilePath;
      let _duration = Math.ceil(res.duration / 1000);
      innerAudioContext.src = _tempPath;
      
      var miao = 540 * (_duration / 600)
      if (miao < 120) {
        miao = 120
      }
      if (_duration > 60) {    //大于60秒转化成分保留两位小数
        _duration = (_duration / 60).toFixed(2)
      }else{
        if (_duration < 10){
          _duration = '0.0' + _duration
        }else{
          _duration = '0.' + _duration
        }
       
      }
      _this.setData({
        soundRecording: {
          tempPath: _tempPath,
          duration: _duration,
          isPlay: false,
          play: false
        },
        width: miao + 'rpx'
      });
      console.log(_this.data.soundRecording.duration)      
      var tempPath = _this.data.soundRecording.tempPath
      if (tempPath) {
        wx.uploadFile({
          url: router.msg.upload,
          filePath: tempPath,
          name: 'file',
          success: function (res) {
            var result = JSON.parse(res.data);
            if (result.status) {
              _this.setData({
                yinpin: result.path
              })
            }
          }
        })
      }
    });
    wx.pauseBackgroundAudio({

    });
  },
  /**
   * 录音播放
   */
  soundRecordingPlay: function () {
    let _this = this;
    let _paused = innerAudioContext.paused;
    let _soundRecording = _this.data.soundRecording;
    if (_paused) {
      innerAudioContext.play();
      _soundRecording.isPlay = true;
      this.time();
      setTimeout(function () {
        let _soundRecording = _this.data.soundRecording;
        _soundRecording.isPlay = false;

        _this.setData({
          soundRecording: _soundRecording
        });
      }, _soundRecording.duration * 1000)
    } else {
      innerAudioContext.stop();
      _soundRecording.isPlay = false;
      clearInterval(_this.time());
      _this.setData({
        isnum: 3
      })
    }
    _this.setData({
      soundRecording: _soundRecording
    });
  },
  time: function () {
    var _this = this;
    setInterval(function () {
      if (_this.data.soundRecording.isPlay) {
        switch (_this.data.isnum) {
          case 1:
            _this.setData({
              isnum: 2,
            })
            break;
          case 2:
            _this.setData({
              isnum: 3,
            })
            break;
          case 3:
            _this.setData({
              isnum: 1,
            })
            break;
        }
      } else {
        _this.setData({
          isnum: 3,
        })
      }

    }, 500);
  },
  /**
   * 删除录音
   */
  soundRecordingRemove: function () {  
    this.setData({
      start: "开始"
    })
    let _this = this;
    innerAudioContext.stop();
    _this.setData({
      soundRecording: {
        tempPath: "",
        duration: "",
        isPlay: false
      },
      yinpin: ""
    });
  },
  //分享
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      var that = this;
      // 来自页面内转发按钮    
      var id = res.target.dataset.id;
      var index = res.target.dataset.ctr;
      var title = that.data.list[index].name;
      return {
        title: title,
        path: '/pages/energy/energy',
        success: function (res) {
          app.request({
            url: router.msg.share,
            method: "POST",
            data: {
              id: id,
            },
            success: function (data) {
              if (data) {
                var list = that.data.list;
                var share = list[index].share;
                list[index].share = share + 1;
                that.setData({
                  list: list
                })
                wx.showToast({
                  title: '分享成功',
                  icon: 'success',
                  duration: 2000
                });
              } else {
                wx.showToast({
                  title: '分享失败请重试',
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          });
        },
        fail: function (res) {
          wx.showToast({
            title: '分享已取消',
            icon: 'none',
            duration: 2000
          });
        }
      }
    }
  },
})